package net.xinqushi.pthread.pthreadlocal;

/**
 *  <b>测试threadLocal 变量回收。</b>
 *  <p>结论，存强引用线程死亡回收,存弱引用gc调用回收。</p>
 *  <p>个人理解: ThreadLocalMap.Entry 是一个WeakReference ，而类内部又定义了value值
 *  此value是用户自定义的。</p><p>一般情况是：该value是一个StrongReference,那么需要该value被回收
 *  Entry才能被回收，故而存强引用线程死亡回收。<p>如果value是一个是一个WeakReference，那么Entry
 *  的key,value值都是WeakReference,只要未被程序使用，gc就会回收。
 *
 * @see  net.xinqushi.gc.RefGC#main
 * @see  net.xinqushi.gc.ReferenceDemo#main
 */
public class ThreadLocalRef {
    public static void main(String[] args) {
        ThreadLocalRef key = new ThreadLocalRef();
        ThreadLocal<ThreadLocalRef> local = new ThreadLocal<ThreadLocalRef>();
        local.set(key);
        local = null;
        Thread main = Thread.currentThread();
        new Thread(
            ()->{
                 for(;true;){
                    System.out.println("finalizing ....");
                    System.gc();
                    try {
                        if(null!= main&&main.isAlive())
                            Thread.sleep(1*1000L);//1s
                        else
                            break;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        ).start();
        try {
            Thread.sleep(5*1000L);//5s
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println(this.getClass()+ " is finalized");
    }
}
